#coding=utf-8

import threading
from views.view_base import *
from common.middlewares import *
from conf.constant import *
from controller.synchronization_controller import SynchronizationController


# 同步数据
class SynchronizationView(ViewBase):
    @dispatch('/synchronous_data', methods=['GET', 'POST'])
    @verify_params(task_id='int')
    def synchronous_data(self):
        code = RESPONSE_FAILED
        data = {}
        msg = '同步失败'

        try:
            task_id = self.params.get('task_id', '')

            controller = SynchronizationController()
            # controller.synchronous_data(task_id)
            t = threading.Thread(target=controller.synchronous_data,
                                 args=(task_id,), name='线程: 物体同步' )
            t.start()
            return self._render.render_json(code=RESPONSE_SUCCESS, data=data, msg='同步中')
        except:
            writelog(traceback.format_exc())
        return self._render.render_json(code=code, data=data, msg=msg)

    @dispatch('/get_progress', methods=['GET', 'POST'])
    @verify_params(task_id='int')
    def get_progress(self):
        code = RESPONSE_FAILED
        data = {}
        msg = '失败'

        try:
            task_id = self.params.get('task_id', '')
            controller = SynchronizationController()
            result = controller.get_progress(task_id)
            code = RESPONSE_SUCCESS
            data = result
            msg = 'success'
        except:
            writelog(traceback.format_exc())
        return self._render.render_json(code=code, data=data, msg=msg)
